/*
 * key.c
 *
 * Created: 2012-10-04 18:58:12
 *  Author: ur
 */ 
#include <avr/io.h>
#include "key.h"
#include "obsluga_menu.h"
#include "enkoder.h"
#include <avr/interrupt.h>

volatile uint8_t button=255;

//#include <util/delay.h>
#define BUTTON_PORT_1  PINA
#define BUTTON_PORT_2  PINC
#define BUTTON_BIT_UP  2
#define BUTTON_BIT_DW 3
#define BUTTON_BIT_LEFT  4
#define BUTTON_BIT_RIGHT  5
#define BUTTON_BIT_OK  6
 #define ENKODER_BIT_OK  7
#define  ENKODER_BIT_LEFT  6
#define ENKODER_BIT_RIGHT  7

 void init_key (void)
 {		
	 DDRA&=~(1<<PA2)|(1<<PA3)|(1<<PA4)|(1<<PA5)|(1<<PA6)|(1<<PA7);		//ustawienie kierunku portu na wejscie
	 PORTA|=(1<<PA2)|(1<<PA3)|(1<<PA4)|(1<<PA5)|(1<<PA6)|(1<<PA7);	//podciagniecie wejsc

 } ;

void czytaj_klawisze(void)
{	//int8_t tmp_enkoder;
	static uint8_t bstate_up = 0; //ostatnie stany przycisku
	static uint8_t bstate_dw = 0;	
	static uint8_t bstate_left = 0;
	static uint8_t bstate_right = 0;
	static uint8_t bstate_ok = 0;
	static uint8_t bstate_enkoder_ok =0;
	static uint8_t bstate_enkoder_left=0;
	//static uint8_t bstate_enkoder_right=0;
	
	
	
	
	if ((bstate_up = (bstate_up << 1 & 0xf) |
	(~BUTTON_PORT_1 >> BUTTON_BIT_UP & 1)) == 1)
	button= e_key_up;
	
	
	if ((bstate_dw = (bstate_dw << 1 & 0xf) |
	(~BUTTON_PORT_1 >> BUTTON_BIT_DW & 1)) == 1)
	button= e_key_down;
	
	
	if ((bstate_left = (bstate_left << 1 & 0xf) |
	(((~BUTTON_PORT_1) >> BUTTON_BIT_LEFT) & 1)) == 1)
	button= e_key_left;
	
	if ((bstate_right = (bstate_right << 1 & 0xf) |
	(~BUTTON_PORT_1 >> BUTTON_BIT_RIGHT & 1)) == 1)
	button= e_key_right;
	
	if ((bstate_ok = (bstate_ok << 1 & 0xf) |
	(~BUTTON_PORT_1 >> BUTTON_BIT_OK & 1)) == 1)
	button= e_key_ok;
	
	if ((bstate_enkoder_ok = (bstate_enkoder_ok << 1 & 0xf) |
	(~BUTTON_PORT_1 >> ENKODER_BIT_OK & 1)) == 1)
	{
		
	button= e_enkoder_push;
	
	}	
	
	if ((bstate_enkoder_left = (bstate_enkoder_left << 1 & 0xf) |
	(~BUTTON_PORT_2 >> ENKODER_BIT_LEFT & 1)) == 1)
	{	if((~BUTTON_PORT_2 >> ENKODER_BIT_RIGHT & 1) == 1)
			{
				button= e_enkoder_left;
			}
		else
			{
				button= e_enkoder_right;
			};
			
						
			
	
	}
	
	
	// byl zwolniony, teraz jest wcisniety - zmiana stanu LED
	//LED_PORT->ODR ^= 1 << GREEN_LED_BIT | 1 << BLUE_LED_BIT;
	
	
	/////////////////////////////////////////////////////////////
	//obsluga enkodera
	////////////////////////////////////////////////////////////
// 	enkoder();
// 	tmp_enkoder=encode_read2();
// 	if(tmp_enkoder<0)button=e_enkoder_left;
// 	if(tmp_enkoder>0)button=e_enkoder_right;
// 	
}

uint8_t wcisniety_klawisz (void)
{	cli();
	uint8_t tmp_button=button;
	button=255;
	sei();
	return tmp_button;
	
}